package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import service.PutCache;
import service.Util;

import model.News;
import model.NewsRecent;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

@SuppressWarnings("serial")
public class CategoryServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");
		
		String path = ((HttpServletRequest)req).getRequestURI();
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 

        String page = "1";
        
		// skip one token /question/abcd (remove sites)
		st.nextToken();
		String title_url = st.nextToken();
		
		if(count != 2 && count != 3)
        {
        	try {
				req.getRequestDispatcher("/404error.jsp").forward(req, resp);
			} catch (Exception e) {
				e.printStackTrace();
			}
        	return ;
        }
		if(count == 3)
		{
			page = st.nextToken();
		}
	
		for (int i = 0; i < page.length(); i++) {
			 if ((page.charAt(i) >= 'A' && page.charAt(i) <= 'Z') || (page.charAt(i) >= 'a' && page.charAt(i) <= 'z')) {
				 resp.sendRedirect("/");
	             break;
	         }
        }
		
		
		if(title_url!=null)
		{
			try {
				ObjectifyService.register(News.class);
			} catch (Exception e) {
				//e.printStackTrace();
			}
			Objectify objectify = ObjectifyService.begin();
			int offset = (Integer.parseInt(page)-1)*20;
			
			ArrayList<NewsRecent> newCategory = PutCache.getCacheNews("list"+title_url+page);
			if(newCategory.size()<=0)
			{
				Query<News> list = objectify.query(News.class).filter("categoryAlias", title_url).order("-date").offset(offset).limit(20);
				ArrayList<News> arrayList = Util.convertArrayList(list);
				
				for(int i=(arrayList.size()-1);i>=0;i--)
				{
					NewsRecent newsRecent = new NewsRecent();
					newsRecent.setDate(arrayList.get(i).getDate());
					newsRecent.setThumb(arrayList.get(i).getThumb());
					newsRecent.setTitle(arrayList.get(i).getTitle().getValue());
					newsRecent.setCategory(arrayList.get(i).getCategory());
					newsRecent.setDes(Util.cutDescription(arrayList.get(i).getContent().getValue()));
					
					PutCache.putCacheNews(newsRecent, "list"+title_url+page, 20);
				}
			}
			
			ArrayList<String> category = PutCache.getCacheList("category");
			
			ArrayList<Query<News>> listCate = new ArrayList<Query<News>>(); 
			if(category.size()>0)
			{
				for (int j = 0; j < category.size(); j++) {
					ArrayList<NewsRecent> cacheCcategory = PutCache.getCacheNews(category.get(j));
					if(cacheCcategory.size()<=0)
					{
						Query<News> list1 = objectify.query(News.class).filter("categoryAlias", category.get(j)).order("-date").limit(5);

						ArrayList<News> arrayList = Util.convertArrayList(list1);
						
						for(int i=(arrayList.size()-1);i>=0;i--)
						{
							NewsRecent newsRecent = new NewsRecent();
							newsRecent.setDate(arrayList.get(i).getDate());
							newsRecent.setThumb(arrayList.get(i).getThumb());
							newsRecent.setTitle(arrayList.get(i).getTitle().getValue());
							newsRecent.setCategory(arrayList.get(i).getCategory());
							newsRecent.setDes(Util.cutDescription(arrayList.get(i).getContent().getValue()));
							
							PutCache.putCacheNews(newsRecent, category.get(j), 5);
						}
						
					}
				}
			}
			
			req.setAttribute("listCate", listCate);
			req.setAttribute("category", title_url);
			req.setAttribute("page", page);
		}
		try {
			req.getRequestDispatcher("/category.jsp").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
